#! /bin/sh
#
# This script is RPM-specific
# It is run at the very end of an install/upgrade of the package
# It is NOT run on removal of the package
#
# .rpm: STEP 6 of 6

INSTALL_DIR=/opt/datadog-agent
CONFIG_DIR=/etc/datadog-agent
SERVICE_NAME=datadog-agent

# Create a symlink to the agent's binary
ln -sf $INSTALL_DIR/bin/agent/agent /usr/bin/datadog-agent

echo "Enabling service $SERVICE_NAME"
if command -v systemctl >/dev/null 2>&1; then
    systemctl enable $SERVICE_NAME || echo "[ WARNING ]\tCannot enable $SERVICE_NAME with systemctl"
elif command -v initctl >/dev/null 2>&1; then
    # start/stop policy is already defined in the upstart job file
    :
else
    echo "[ WARNING ]\tCannot detect a supported init system. The datadog-iot-agent package only provides service files for systemd and upstart."
fi

# Set the installation information if not already present;
# This is done in the postinst script for .deb packages
if [ ! -f "$CONFIG_DIR/install_info" ]; then

    if command -v rpm >/dev/null 2>&1; then
        tool=rpm
        # Omnibus will put this script verbatim inside RPM specfile before building.
        # We need to escape the "%" so that the rpm build machinery doesn't expand
        # it as a macro (which would expand to the version of Agent being built).
        # NOTE: on some distros (e.g. opensuse 15.4), "rpm" package doesn't exist,
        # it's called "rpm-ndb". We query version of package which contains /bin/rpm file.
        tool_version=rpm-$(rpm -q -f /bin/rpm --queryformat "%%{VERSION}" || echo "unknown")
    else
        tool=unknown
        tool_version=unknown
    fi

    install_info_content="---
install_method:
  tool: $tool
  tool_version: $tool_version
  installer_version: rpm_package-iot
"
    echo "$install_info_content" > $CONFIG_DIR/install_info
    chown -R dd-agent:dd-agent ${CONFIG_DIR}
fi

# TODO: Use a configcheck command on the agent to determine if it's safe to restart,
# and avoid restarting when a check conf is invalid
if [ -f "$CONFIG_DIR/datadog.yaml" ]; then
    echo "(Re)starting $SERVICE_NAME now..."
    if command -v systemctl >/dev/null 2>&1; then
        systemctl restart $SERVICE_NAME || true
    elif command -v initctl >/dev/null 2>&1; then
        initctl start $SERVICE_NAME || initctl restart $SERVICE_NAME || true
    else
        echo "[ WARNING ]\tCannot detect a supported init system. The datadog-iot-agent package only provides service files for systemd and upstart."
    fi
else
    # No datadog.yaml file is present. This is probably a clean install made with the
    # step-by-step instructions/an automation tool, and the config file will be added next.
    echo "No datadog.yaml file detected, not starting the agent"
fi

exit 0
